package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.brwh.kit.StrKit;
import com.seeyon.apps.brwh.service.ExportMxTableDataService;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Path("jssdk")
@Produces({"application/json"})
@Consumes({"application/json"})
public class ExportMxTableDataResources extends BaseResource  {
    private static final Log log = CtpLogFactory.getLog(ExportMxTableDataResources.class);
    private ExportMxTableDataService sketchMapFiledExcelService = (ExportMxTableDataService) AppContext.getBean("exportMxTableDataService");


    /**
     * 缓存导出明细数据
     * @param param
     * @throws IOException
     */
    @POST
    @Path("brwh/cacheMxTableData")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response cacheMxTableData(Map<String, Object> param){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        log.info("自定义导出明细表按钮数据请求："+ JSONObject.toJSONString(param));
        try {
            List<Map<String, Object>> subDataList = (List<Map<String, Object>>)param.get("subDataList");
            if(subDataList.isEmpty()){
                resultMap.put("code","500");
                resultMap.put("data",null);
                resultMap.put("msg", "下载数据不能为空！！！！");
            }
            String s = sketchMapFiledExcelService.cacheExcelData(param);
            if(!s.equals("-1")){
                resultMap.put("code","200");
                resultMap.put("data",s);
                resultMap.put("msg", "");
            }else{
                resultMap.put("code","500");
                resultMap.put("data","-1");
                resultMap.put("msg", "缓存下载明细表数据异常");
            }
        }catch (Exception e) {
            log.info("自定义导出数据异常："+ e);
            resultMap.put("code","500");
            resultMap.put("data","-1");
        }
        return ok(JSON.toJSONString(resultMap));
    }



    /**
     * 缓存导出明细数据
     * @throws IOException
     */
    @GET
    @Path("brwh/exportMxTableData")
    public void exportMxTableData() throws IOException {
        String uuid = req.getParameter("uuid");
        if(uuid.equals("")){
            resp.getWriter().print("<center><b style=\"color:red;\">下载数据Excel异常：参数uuid不能为null</b></center>");
            return;
        }
        try {
            sketchMapFiledExcelService.ExportMxTableData(resp,uuid);
        }catch (Exception e) {
            log.info("自定义导出数据异常："+ e);
            resp.getWriter().print("<center><b style=\"color:red;\">下载数据Excel异常"+e+"</b></center>");
        }
    }


    /**
     * 导出Excel数据模板
     * @throws IOException
     */
    @GET
    @Path("brwh/downLoadExcelTemp")
    public void downLoadExcelTemp() throws IOException {
        String uuid = req.getParameter("uuid");
        if(uuid == null || uuid.equals("")){
            resp.getWriter().print("<center><b style=\"color:red;\">下载模板的下载码异常</b></center>");
            return;
        }
        try {
            sketchMapFiledExcelService.downLoadExcelTemp(uuid,resp);
        }catch (Exception e) {
            log.info("自定义导出数据异常："+ e);
            resp.getWriter().print("<center><b style=\"color:red;\">下载数据Excel模板异常"+e+"</b></center>");
        }
    }



    @Path("brwh/importFileData")
    @POST
    @Produces({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON })
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response financeImportExcel() throws IOException {
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        MultipartResolver resolver = new CommonsMultipartResolver(req.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(req);
        MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
        List<MultipartFile> multipartFiles =  multiFileMap.get("fileText");
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile multipartFile = fileMap.get("fileText");
        if(multipartFile == null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("status",0);
            map.put("data",null);
            map.put("msg", "上传文件不能为空！！！！");
            return ok(map);
        }

        InputStream inputStream = multipartFile.getInputStream();
        String originalFilename = new String(multipartFile.getOriginalFilename().getBytes("ISO-8859-1"),"utf-8");
        HashMap<String, Object> importExcelTemp = null;
        try {
            importExcelTemp = sketchMapFiledExcelService.impotExcleData(inputStream, originalFilename);
        } catch (BusinessException e) {
            log.info("导入Excel数据异常："+e);
            HashMap<String, Object> map = new HashMap<>();
            map.put("status",0);
            map.put("data",null);
            map.put("msg", "导入Excel数据异常，请检查日志");
            return ok(map);
        }
        return ok(importExcelTemp);
    }
}
